package com.yanqu.road.server.cmd.stelesoul;

import com.yanqu.road.entity.activity.stelesoul.SteleSoulUserData;
import com.yanqu.road.entity.activity.stelesoul.config.SteleSoulConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.SteleSoulProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.stelesoul.SteleSoulModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.stelesoul.SteleSoulMgr;
import com.yanqu.road.server.pb.SteleSoulPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

@Cmd(code = GameProtocol.S_STELE_SOUL_ACTIVITY_INSERT, desc = "请求石碑注魂(抽奖)")
public class SteleInsertSoulCmd extends AbstractCommand {
    private int times = 0;  // 抽取次数

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        SteleSoulProto.SteleInsertSoulReqMsg reqMsg = SteleSoulProto.SteleInsertSoulReqMsg.parseFrom(packet.getBytes());
        times = reqMsg.getTimes();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        SteleSoulConfig config = SteleSoulMgr.getSteleSoulConfig();
        if (config == null || !ActivityMgr.activityInTimeAndShowTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_ACTIVITY_HAD_END;
            return;
        }
        SteleSoulUserData userData = player.getModule(SteleSoulModule.class).getSteleSoulUserData();
        if (userData == null) {
            ret = GameErrorCode.E_SYSTEM_NO_OPEN;
            return;
        }
        ret = player.getModule(SteleSoulModule.class).insert(times);
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            SteleSoulProto.SteleInsertSoulRespMsg.Builder builder = SteleSoulProto.SteleInsertSoulRespMsg.newBuilder();
            builder.setRet(ret);
            builder.setIsEgg(false);
            SteleSoulUserData userData = player.getModule(SteleSoulModule.class).getSteleSoulUserData();
            if (userData == null) {
                SteleSoulProto.SteleSoulUserDataMsg.Builder userBuilder = SteleSoulProto.SteleSoulUserDataMsg.newBuilder();
                userBuilder.setRoundTimes(0);
                userBuilder.setLoop(0);
                userBuilder.setLastIndex("");
                builder.setUserData(userBuilder);
            }else {
                builder.setUserData(SteleSoulPb.parseSteleSoulUserDataMsg(player.getModule(SteleSoulModule.class).getSteleSoulUserData()));
            }
            player.sendPacket(ClientProtocol.U_STELE_SOUL_INSERT, builder);
        }
    }
}
